package com.zyh.web;

import com.alibaba.fastjson2.JSONObject;
import com.zyh.core.AjaxResult;
import com.zyh.core.BaseHttpServlet;
import com.zyh.dao.impl.UserDaoImpl;
import com.zyh.domain.User;
import com.zyh.service.IUserService;
import com.zyh.service.impl.UserServiceImpl;
import com.zyh.utils.RequestUtils;
import com.zyh.utils.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/user/*")
public class LoginServlet extends BaseHttpServlet {

    private IUserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserServiceImpl(new UserDaoImpl());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();

        switch (pathInfo) {
            case "/login":
                // 实现登录功能
                JSONObject jsonObject = RequestUtils.getReqJsonBody(req, JSONObject.class);
                // 执行逻辑
                executeBusiness(resp, response -> {
                    User user = userService.login(jsonObject.getString("username"), jsonObject.getString("password"));
                    // 登录成功
                    // 设置登录用户
                    req.getSession().setAttribute("user", user);
                    ResponseUtils.responseJson(resp, AjaxResult.success(user));
                });
                break;
            case "/register":
                // 实现注册的逻辑
                User user = RequestUtils.getReqJsonBody(req, User.class);
                executeBusiness(resp, response -> {
                    ResponseUtils.responseJson(resp, AjaxResult.success(userService.register(user)));
                });
        }

    }


}
